import { listPost } from '@/api/system/post'
import { listChannel } from '@/api/erp/channel'
import { listToTreeOptions } from '@/utils/utils'
import store from '../index'

function effect(key, value) {
  if (value.length === 0) {
    store.dispatch('market/send', key)
  }
  return value
}

function getKey(key) {
  return `market::${key}`
}

async function setDict(key) {
  let rows = await getRequest(key.type, key)
  const market = JSON.stringify({
    updateTime: new Date(),
    value: rows || [],
  })
  Promise.resolve().then(() => localStorage.setItem(getKey(key.type), market))

  return rows
}

async function getRequest(value, key) {
  if (value == 'listPost') {
    const { rows } = await listPost(key)
    return rows
  }
  if (value == 'listChannel') {
    const { rows } = await listChannel(key)
    const options = listToTreeOptions(rows, ({ pid, id, name }) => ({
      parentId: pid,
      id,
      label: name,
      value: name,
    }))
    // options.unshift({
    //   label: '直接上门',
    //   value: '直接上门',
    // })
    return options
  }
}

async function markets(key) {
  const json = JSON.parse(localStorage.getItem(getKey(key.type)))
  if (json) {
    const { updateTime, value } = json

    const time = new Date(updateTime).toLocaleDateString()
    const currentTime = new Date().toLocaleDateString()

    if (value && value.length !== undefined && time === currentTime) {
      return value
    }
  }
  return setDict(key)
}

export default {
  namespaced: true,
  state: {
    listPost: [],
    listPostParams: {
      pageNum: 1,
      pageSize: 1000,
      postCode: 'market',
      status: '0',
      type: 'listPost',
    },
    listChannel: [],
    listChannelParams: {
      pageNum: 1,
      pageSize: 10000,
      status: '1',
      type: 'listChannel',
    },
  },
  mutations: {
    save(state, { key, value }) {
      state[key.type] = value
    },
  },
  actions: {
    async send({ commit }, key) {
      commit('save', { key, value: await markets(key) })
    },
  },
  getters: {
    //市场部门列表
    marketPostList({ listPostParams, listPost }) {
      return effect(listPostParams, listPost)
    },
    marketChannelList({ listChannelParams, listChannel }) {
      return effect(listChannelParams, listChannel)
    },
  },
}
